$(function () {
    //设置弹框
    texiao()
    $('.showcontentbtn')
    // caidai()
    //     // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
    // $(document).on('show.bs.modal', '.modal', function (event) {
    //         var zIndex = 1040 + (10 * $('.modal:visible').length);
    //         $(this).css('z-index', zIndex);
    //         setTimeout(function() {
    //             $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    //         }, 0);
    // });
    var articleid = getQueryString('id')
    // 评论对象
    var CommentCreateVO = new FormData()
    // 收藏夹的id
    var starid = ''
    init(articleid)
    function init(articleid) {
        $.ajax({
            url:'/unAuthorize/getArticle?id='+articleid,
            type:'Get',
            dataType: "json",
            // async: true,
            processData: false,   // 不处理发送的数据
            contentType: false,   // 不设置Content-Type请求头
            success:function (res) {
                console.log(res)
                if(res.code==200){
                    var article = res.data.article
                    var user = res.data.user
                    var commentList = res.data.commentList
                    // console.log(articcle.categories)
                    var categoriesarr = article.categories.split(',')
                    var tagarr = article.tags.split(',')
                    // 博主渲染
                    $('.userimg').attr('src',user.img)
                    $('.bloggername').text(user.username)
                    $('.fansnum').text(user.followedNumber)
                    $('.userid').text(user.id)
                    // 博主收藏数
                    $('.usercommendnum').text(user.collectNumber)
                    // 关注
                    $('.userlikednum').text(user.followingNumber)
                    $('.userarticlenum').text(res.data.articleNumber)
                    $('.userclicknum').text(res.data.clickNumber)
                    //文章渲染
                    $('.articlename').text(article.title)
                    $('.looknum').text(article.clickNumber)
                    $('.collectedNumber').text("收藏 "+article.collectedNumber)
                    $('.suplike').text(article.likeNumber)
                    $('.supcomment').text(article.commentNumber)
                    $('.supcollect').text(article.collectedNumber)
                    $('.articletime').text(article.createTime)
                    $('.articlemain').html(article.content)
                    CommentCreateVO.append('title',article.title)
                    CommentCreateVO.append('userId',user.id)
                    CommentCreateVO.append('articleId',article.id)
                    isFollow(user.id)
                    if (article.isComment==false)
                    {
                        $('#textcomment').attr('placeholder','博主关闭了评论')
                        $('#textcomment').attr('disabled','disabled')

                    }
                    for (let i=0;i<tagarr.length;i++){
                        let str = '<span class="articletitle">'+tagarr[i]+'</span>'
                        $('.articletitleli').append(str)
                    }
                    for (let i=0;i<categoriesarr.length;i++){
                        let str = '<span class="articlecate">'+categoriesarr[i]+'</span>'
                        $('.articlecateli').append(str)
                    }
                    for (let i=0;i<commentList.length;i++){
                        let str = '<li>\n' +
                            '<img src="/dist/img/avatar2.png" alt="" class="img-circle userimg">\n' +
                            '<span class="commentname">'+commentList[i].author+'</span><span>: </span>\n' +
                            '<span>'+commentList[i].content+'</span>\n' +
                            '</li>'
                        $('.commentuili').append(str)
                    }
                }
                else{
                    $.toast({
                        title: '通知',
                        subtitle: '1秒前',
                        content: res.msg,
                        type: 'error',
                        delay: 1000,
                        pause_on_hover: false
                    })
                    return;
                }
            }
        })



    }
    $('.nologin').click(function () {
        window.location.href='/unAuthorize/login'
    })
    $('.tomainbtn').click(function () {
        var id = $('.userid').text()
        console.log(id)
        window.location.href='/unAuthorize/blogger?id='+id
    })
    $('.followbtn').click(function() {
        var id = $('.userid').text()
        console.log($('.followbtn').text())
        // 元素有这个类就移除，没有就加上
        if($('.followbtn').text()=='关注')
        {
            $.ajax({
                url: '/following/following?id='+id,
                type: 'GET',
                dataType: "json",
                // data:userid,
                // async: true,
                processData: false,   // 不处理发送的数据
                contentType: false,   // 不设置Content-Type请求头
                success:function (res) {
                    if (res.code == 200) {
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content: '关注成功',
                            type: 'success',
                            delay: 3000,
                            pause_on_hover: false
                        });
                        $('.followbtn').text('取消关注')
                        $('.followbtn').addClass('isfollow')
                    } else {
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content: res.msg,
                            type: 'error',
                            delay: 3000,
                            pause_on_hover: false
                        });
                        return;
                    }

                }
            })
            //发送关注请求
        }
        else{
            $.ajax({
                url: '/following/delete?id='+id,
                type: 'GET',
                dataType: "json",
                // data:userid,
                // async: true,
                processData: false,   // 不处理发送的数据
                contentType: false,   // 不设置Content-Type请求头
                success:function (res) {
                    if (res.code == 200) {
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content:'取消了关注',
                            type: 'success',
                            delay: 3000,
                            pause_on_hover: false
                        });
                        $('.followbtn').text('关注')
                        $('.followbtn').removeClass('isfollow')
                    } else {
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content: res.msg,
                            type: 'error',
                            delay: 3000,
                            pause_on_hover: false
                        });
                        return;
                    }

                }
            })


        }
    })

    $("#textcomment").keyup(function () {
        var len = $(this).val().length;
        if (len > 299) {
            $(this).val($(this).val().substring(0, 300));
        }
        $("#word").text(300-len);
    });
    // 文本框动画
    $('#textcomment').focus(function () {
        // $(this).addClass('active')
        $(this).animate({height:60},1000,'swing',function () {
            $(this).addClass('active')
            $('.textnum').show(500)
        })
    })
    // 提交评论
    $('.commentbtn').click(function () {
        console.log($('#textcomment').val())
        if ($('#textcomment').val().length==0){
            alert("请输入内容再提交")
            return
        }
        else{
            //发请求
            CommentCreateVO.append('content',$('#textcomment').val())
            console.log(CommentCreateVO)
            $.ajax({
                url: '/comment/insert',
                type: 'POST',
                data: CommentCreateVO,
                dataType: "json",
                // async: true,
                processData: false,   // 不处理发送的数据
                contentType: false,   // 不设置Content-Type请求头
                success: function (res){
                    if (res.code==200){
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content: "你的评论是博主进步的良言",
                            type: 'success',
                            delay: 1000,
                            pause_on_hover: false,
                        })
                        window.setInterval(function () {
                            window.location.href = '/unAuthorize/article?id='+articleid;
                        },1000)
                    }
                    else{
                        $.toast({
                            title: '通知',
                            subtitle: '1秒前',
                            content: res.msg,
                            type: 'error',
                            delay: 1000,
                            pause_on_hover: false
                        })

                    }

                }
            })



        }
    })
    // 点赞
    $('.likebtn').click(function () {
        var userid = $('.userid').text()
        console.log(userid,articleid)
        $.ajax({
            url:'/article/liking?id='+articleid+'&aid='+userid,
            type: 'GET',
            // data:param,
            dataType: "json",
            // async: true,
            processData: false,   // 不处理发送的数据
            contentType: false,   // 不设置Content-Type请求头
            success:function (res) {
                console.log(res)
                if (res.code==200){
                    $.toast({
                        title: '通知',
                        subtitle: '1秒前',
                        content: '点赞成功',
                        type: 'success',
                        delay: 3000,
                        pause_on_hover: false
                    })
                    $('.fa-thumbs-up').addClass('likeactive')

                    var likenum = $('.suplike').text()
                    likenum = Number(likenum)+1


                    $('.suplike').text(likenum)

                }
                else {
                    $.toast({
                        title: '通知',
                        subtitle: '1秒前',
                        content: res.msg,
                        type: 'error',
                        delay: 3000,
                        pause_on_hover: false
                    });
                    return;
                }
            }
        })
    })
    $('.starnum').click(function () {
        $.ajax({
            url:'/collectCategories/list',
            type: 'GET',
            // data:param,
            dataType: "json",
            // async: true,
            processData: false,   // 不处理发送的数据
            contentType: false,   // 不设置Content-Type请求头
            success:function (res) {
                console.log(res)
                var data = res.data
                if (res.code==200){
                    $('.colletc-list').children().remove()
                    for (let i = 0; i < data.length; i++) {
                        if(data[i]){
                            var $str = $('<div class="blogger-list-li">\n' +
                                '<div class="blogger-list-title"><div class="collectid" style="display: none">'+data[i].id+'</div>\n' +
                                '<a href="#" title="点击查看文章"><span>'+data[i].name+'</span></a>' +
                                '</div>\n' +
                                '<div class="blogger-list-article">'+data[i].content+'</div>\n' +
                                '<div class="blogger-list-detail">\n' +
                                '<div class="blogger-list-detail-look" >\n' +
                                '<span>'+data[i].articleNumber+'</span><span>篇文章</span>\n' +
                                '</div>\n' +
                                '<div class="blogger-list-detail-time" >\n' +
                                '<span>发布时间:</span><span>'+data[i].createTime+'</span>\n' +
                                '</div>\n' +
                                '</div>\n' +
                                '</div>')
                            $('.colletc-list').append($str)
                        }
                    }
                }
                else {
                    $.toast({
                        title: '通知',
                        subtitle: '1秒前',
                        content: res.msg,
                        type: 'error',
                        delay: 3000,
                        pause_on_hover: false
                    });
                    return;
                }
            }
        })

    })
    $(document).on('click','.blogger-list-li',function () {
        var id = $(this).find('.collectid').text()
        starid = id
        console.log(articleid)
        $(this).addClass('active').siblings('div').removeClass('active')
        console.log(starid)
        $('.addbtn').click(function () {
            $.ajax({
                    url: '/collectCategories/collect?aid='+articleid+'&cid='+id,
                    type: 'Get',
                    dataType: "json",
                    // data: ,  `
                    // async: true,
                    processData: false,   // 不处理发送的数据
                    contentType: false,   // 不设置Content-Type请求头
                    success:
                        function (res) {
                            console.log(res)
                            if (res.code == 200) {
                                $.toast({
                                    title: '通知',
                                    subtitle: '5秒前',
                                    content: res.data,
                                    type: 'success',
                                    delay: 1000,
                                    pause_on_hover: false
                                });
                                window.setInterval(function () {
                                    window.location.href = '/unAuthorize/article?id='+articleid;
                                },1000)
                            } else {
                                $.toast({
                                    title: '通知',
                                    subtitle: '5秒前',
                                    content: res.msg,
                                    type: 'error',
                                    delay: 1000,
                                    pause_on_hover: false
                                });
                                window.setInterval(function () {
                                    window.location.href = '/unAuthorize/article?id='+articleid;
                                },1000)
                            }
                            return ;
                        },
                    error:function () {
                        alert("已经收藏了，请勿重复收藏")
                        // window.setInterval(function () {
                        //     window.location.href = '/unAuthorize/article?id='+articleid;
                        // },1000)
                    }
                })
        })
    })
    $('.adddataForm').off().submit(function () {
        var CollectCreateVO = new FormData();
        console.log(articleid)
        CollectCreateVO.append("name", $(".adddataForm input[name='name']").val())
        CollectCreateVO.append("isShow", $(".adddataForm input[name='show']:checked").val())
        CollectCreateVO.append("content", $(".adddataForm textarea[name='content']").val())
        // var TypeCreateVO=$('.adddataForm').serialize();
        console.log(CollectCreateVO)
        $.ajax({
                url: '/collectCategories/insert',
                type: 'POST',
                dataType: "json",
                data: CollectCreateVO,
                // data: ,
                // async: true,
                processData: false,   // 不处理发送的数据
                contentType: false,   // 不设置Content-Type请求头
                success:
                    function (res) {
                        console.log(res)
                        if (res.code == 200) {
                            $.toast({
                                title: '通知',
                                subtitle: '5秒前',
                                content: res.data,
                                type: 'success',
                                delay: 1000,
                                pause_on_hover: false
                            });
                            window.setInterval(function () {
                                window.location.href = '/unAuthorize/article?id='+articleid;
                            },1000)
                        } else {
                            $.toast({
                                title: '通知',
                                subtitle: '5秒前',
                                content: res.msg,
                                type: 'error',
                                delay: 1000,
                                pause_on_hover: false
                            });
                        }
                    }
            }
        )
        return false;
    })
    qiu()


    function texiao() {
            var hearts = [];
            window.requestAnimationFrame = (function(){
                return window.requestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    window.oRequestAnimationFrame ||
                    window.msRequestAnimationFrame ||
                    function (callback){
                        setTimeout(callback,1000/60);
                    }
            })();
        inittexiao();
            function inittexiao(){
                css(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
                attachEvent();
                gameloop();
            }
            function gameloop(){
                for(var i=0;i<hearts.length;i++){
                    if(hearts[i].alpha <=0){
                        document.body.removeChild(hearts[i].el);
                        hearts.splice(i,1);
                        continue;
                    }
                    hearts[i].y--;
                    hearts[i].scale += 0.004;
                    hearts[i].alpha -= 0.013;
                    hearts[i].el.style.cssText = "left:"+hearts[i].x+"px;top:"+hearts[i].y+"px;opacity:"+hearts[i].alpha+";transform:scale("+hearts[i].scale+","+hearts[i].scale+") rotate(45deg);background:"+hearts[i].color;
                }
                requestAnimationFrame(gameloop);
            }
            function attachEvent(){
                var old = typeof window.οnclick==="function" && window.onclick;
                window.onclick = function(event){
                    old && old();
                    createHeart(event);
                }
            }
            function createHeart(event){
                var d = document.createElement("div");
                d.className = "heart";
                hearts.push({
                    el : d,
                    x : event.clientX - 5,
                    y : event.clientY - 5,
                    scale : 1,
                    alpha : 1,
                    color : randomColor(),
                });
                document.body.appendChild(d);
            }
            function css(css){
                var style = document.createElement("style");
                style.type="text/css";
                try{
                    style.appendChild(document.createTextNode(css));
                }catch(ex){
                    style.styleSheet.cssText = css;
                }
                document.getElementsByTagName('head')[0].appendChild(style);
            }
            function randomColor(){
                return "rgb("+(~~(Math.random()*255))+","+(~~(Math.random()*255))+","+(~~(Math.random()*255))+")";
            }

    }
    function qiu() {
        !function () {
            //封装方法，压缩之后减少文件大小
            function get_attribute(node, attr, default_value) {
                return node.getAttribute(attr) || default_value;
            }

            //封装方法，压缩之后减少文件大小
            function get_by_tagname(name) {
                return document.getElementsByTagName(name);
            }

            //获取配置参数
            function get_config_option() {
                var scripts = get_by_tagname("script"),
                    script_len = scripts.length,
                    script = scripts[script_len - 1]; //当前加载的script
                return {
                    l: script_len, //长度，用于生成id用
                    z: get_attribute(script, "zIndex", 0), //z-index
                    o: get_attribute(script, "opacity", 0.8), //opacity
                    c: get_attribute(script, "color", "255,255,255"), //color
                    n: get_attribute(script, "count", 350) //count
                };
            }

            //设置canvas的高宽
            function set_canvas_size() {
                canvas_width = the_canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
                    canvas_height = the_canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            }

            //绘制过程
            function draw_canvas() {
                context.clearRect(0, 0, canvas_width, canvas_height);
                //随机的线条和当前位置联合数组
                var e, i, d, x_dist, y_dist, dist; //临时节点
                //遍历处理每一个点
                random_points.forEach(function (r, idx) {
                    r.x += r.xa,
                        r.y += r.ya, //移动
                        r.xa *= r.x > canvas_width || r.x < 0 ? -1 : 1,
                        r.ya *= r.y > canvas_height || r.y < 0 ? -1 : 1, //碰到边界，反向反弹
                        context.fillRect(r.x - 0.5, r.y - 0.5, 1, 1); //绘制一个宽高为1的点
                    //从下一个点开始
                    for (i = idx + 1; i < all_array.length; i++) {
                        e = all_array[i];
                        // 当前点存在
                        if (null !== e.x && null !== e.y) {
                            x_dist = r.x - e.x; //x轴距离 l
                            y_dist = r.y - e.y; //y轴距离 n
                            dist = x_dist * x_dist + y_dist * y_dist; //总距离, m

                            dist < e.max && (e === current_point && dist >= e.max / 2 && (r.x -= 0.03 * x_dist, r.y -= 0.03 * y_dist), //靠近的时候加速
                                d = (e.max - dist) / e.max,
                                context.beginPath(),
                                context.lineWidth = d / 2,
                                context.strokeStyle = "#000000",
                                context.moveTo(r.x, r.y),
                                context.lineTo(e.x, e.y),
                                context.stroke());
                        }
                    }
                }), frame_func(draw_canvas);
            }

            //创建画布，并添加到body中
            var the_canvas = document.createElement("canvas"), //画布
                config = get_config_option(), //配置
                canvas_id = "c_n" + config.l, //canvas id
                context = the_canvas.getContext("2d"), canvas_width, canvas_height,
                frame_func = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (func) {
                    window.setTimeout(func, 1000 / 40);
                }, random = Math.random,
                current_point = {
                    x: null, //当前鼠标x
                    y: null, //当前鼠标y
                    max: 20000 // 圈半径的平方
                },
                all_array;
            the_canvas.id = canvas_id;
            the_canvas.style.cssText = "position:fixed;top:0;left:0;z-index:" + config.z + ";opacity:" + config.o;
            get_by_tagname("body")[0].appendChild(the_canvas);

            //初始化画布大小
            set_canvas_size();
            window.onresize = set_canvas_size;
            //当时鼠标位置存储，离开的时候，释放当前位置信息
            window.onmousemove = function (e) {
                e = e || window.event;
                current_point.x = e.clientX;
                current_point.y = e.clientY;
            }, window.onmouseout = function () {
                current_point.x = null;
                current_point.y = null;
            };
            //随机生成config.n条线位置信息
            for (var random_points = [], i = 0; config.n > i; i++) {
                var x = random() * canvas_width, //随机位置
                    y = random() * canvas_height,
                    xa = 2 * random() - 1, //随机运动方向
                    ya = 2 * random() - 1;
                // 随机点
                random_points.push({
                    x: x,
                    y: y,
                    xa: xa,
                    ya: ya,
                    max: 6000 //沾附距离
                });
            }
            all_array = random_points.concat([current_point]);
            //0.1秒后绘制
            setTimeout(function () {
                draw_canvas();
            }, 100);
        }();

    }
})

// 获取id
function getQueryString(name) {

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
// 判断是否关注
function isFollow(id) {
    $.ajax({
        url: '/following/isFollow?id=' + id,
        type: 'get',
        dataType: "json",
        // async: true,
        processData: false,   // 不处理发送的数据
        contentType: false,   // 不设置Content-Type请求头
        success:function (res) {
            console.log("关注了吗"+res.data)
            if(res.data==false){
                $('.followbtn').text('关注')
            }
            else {
                $('.followbtn').text('取消关注')
                $('.followbtn').addClass('isfollow')
            }
        }
    })


}

//

// function init(articleid) {
//     $.ajax({
//         url:'/unAuthorize/getArticle?id='+articleid,
//         type:'Get',
//         dataType: "json",
//         // async: true,
//         processData: false,   // 不处理发送的数据
//         contentType: false,   // 不设置Content-Type请求头
//         success:function (res) {
//             console.log(res)
//             if(res.code==200){
//                 var article = res.data.article
//                 var user = res.data.user
//                 var commentList = res.data.commentList
//                 // console.log(articcle.categories)
//                 var categoriesarr = article.categories.split(',')
//                 var tagarr = article.tags.split(',')
//                 // 博主渲染
//                 $('.userimg').attr('src',user.img)
//                 $('.bloggername').text(user.username)
//                $('.fansnum').text(user.followedNumber)
//                 $('.userid').text(user.id)
//                 // 博主收藏数
//                $('.usercommendnum').text(user.collectNumber)
//                 // 关注
//                 $('.userlikednum').text(user.followingNumber)
//                 $('.userarticlenum').text(res.data.articleNumber)
//                 $('.userclicknum').text(res.data.clickNumber)
//                 //文章渲染
//                 $('.articlename').text(article.title)
//                 $('.looknum').text(article.clickNumber)
//                 $('.collectedNumber').text("收藏 "+article.collectedNumber)
//                 $('.suplike').text(article.likeNumber)
//                 $('.supcomment').text(article.commentNumber)
//                 $('.supcollect').text(article.collectedNumber)
//                 $('.articletime').text(article.createTime)
//                 $('.articlemain').text(article.content)
//                 CommentCreateVO.append('title',article.title)
//                 CommentCreateVO.append('userId',user.id)
//                 CommentCreateVO.append('articleId',article.id)
//                 isFollow(user.id)
//                 if (article.isComment==false)
//                 {
//                     $('#textcomment').attr('placeholder','博主关闭了评论')
//                     $('#textcomment').attr('disabled','disabled')
//
//                 }
//                 for (let i=0;i<tagarr.length;i++){
//                     let str = '<span class="articletitle">'+tagarr[i]+'</span>'
//                     $('.articletitleli').append(str)
//                 }
//                 for (let i=0;i<categoriesarr.length;i++){
//                     let str = '<span class="articlecate">'+categoriesarr[i]+'</span>'
//                     $('.articlecateli').append(str)
//                 }
//                 for (let i=0;i<commentList.length;i++){
//                     let str = '<li>\n' +
//                         '<img th:src="@{/dist/img/avatar2.png}" alt="" class="img-circle userimg">\n' +
//                         '<span class="commentname">ljx</span><span>: </span>\n' +
//                         '<span></span>\n' +
//                         '</li>' +
//                     $('.articlecateli').append(str)
//                 }
//             }
//             else{
//                 $.toast({
//                     title: '通知',
//                     subtitle: '1秒前',
//                     content: res.msg,
//                     type: 'error',
//                     delay: 1000,
//                     pause_on_hover: false
//                 })
//                 return;
//             }
//         }
//     })
//
//
//
// }